<template>
  <div>
    <div class="add">
      <el-card class="lh28">
        <div class="addOrderPopout">
          <!-- <div class="titleL">基本信息</div> -->
          <el-form ref="detail" :model="detail" :rules="rules" label-width="120px">

            <el-form-item size="mini" label="姓名" prop="personId">
              <el-select
                v-model.trim="detail.personId"
                filterable
                remote
                reserve-keyword
                class="w280"
                clearable
                placeholder="请输入姓名"
                :loading="loading"
                :remote-method="remoteMethod"
                @keydown.native="trimLR"
                @change="changeName"
              >
                <el-option v-for="item in options.personnel" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item size="mini" label="所属组织" prop="deptIds">

              <el-cascader
                v-if="personType != 2"
                v-model="detail.deptIds"
                class="w280"
                disabled
                :options="options.dept"
                :show-all-levels="false"
                :props="optionProps"
                clearable
                @change="changeDeptIds"
              />
              <el-input v-else v-model="detail.deptName" disabled class="w280" />
            </el-form-item>
            <el-form-item size="mini" label="手机号" prop="tel">
              <el-input v-model="detail.tel" class="w280" />
            </el-form-item>

            <el-form-item size="mini" label="所属角色" prop="roleIds">
              <el-select
                v-model="detail.roleIds"
                multiple
                filterable
                :disabled="selectRole"
                placeholder="请选择"
                class="w280"
                @change="$forceUpdate()"
              >
                <el-option v-for="item in options.role" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item size="mini" label="账号名称" prop="loginname">
              <el-input v-model="detail.loginname" :disabled="nameType != '新增'" class="w280" />
            </el-form-item>
            <el-form-item v-if="nameType=='新增'" size="mini" label="账号密码" prop="passwd">
              <el-input
                ref="passwd"
                v-model="detail.passwd"
                class="w280"
                :type="passwordType"
                placeholder="
8-12位字母与数字组合"
              />
              <div class="show-pwd" @click="showPwd('passwd')">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </div>
            </el-form-item>
            <el-form-item v-if="nameType=='新增'" size="mini" label="重复输入密码" prop="repasswd">
              <el-input
                ref="repasswd"
                v-model="detail.repasswd"
                class="w280"
                placeholder="
8-12位字母与数字组合"
                :type="passwordType"
              />
              <div class="show-pwd" @click="showPwd('repasswd')">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </div>
            </el-form-item>
            <el-form-item size="mini" label="是否允许登录本系统" prop="isDrugLogin" label-width="180px">
              <el-radio-group v-model="detail.isDrugLogin">
                <el-radio :label="false">否</el-radio>
                <el-radio :label="true">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="footer">
              <el-button v-if="nameType != '详情'" type="primary" size="small" @click="createDetail('detail')">提
                交</el-button>
              <el-button size="small" @click="returnUpper">返 回</el-button>
            </div>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { userAdd, userUpdate, ueserDetail } from '@/api/account';
import { getDeptTree } from '@/api/organization';
import { personList } from '@/api/personnel';
import { roleListForYard } from '@/api/role';
class Detail {
  name = '';
  tel = '';
  state = '';
  deptIds = [];
  roleIds = [];
  personId = '';
  loginname = '';
  passwd = '';
  repasswd = '';
  isDrugLogin = false;
}
class Options {
  dept = []
  role = []
  personnel = []
  options = [
    { id: 1, name: '选项一' },
    { id: 2, name: '选项二' },
    { id: 3, name: '选项三' },
    { id: 4, name: '选项四' }
  ];
}
export default {
  name: 'CourtyardAdminDetail',
  data() {
    const repasswd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.detail.passwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      detail: new Detail(), // 分页
      options: new Options(), // 选项
      rules: {
        personId: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        tel: [
          { required: true, message: '请填写联系电话', trigger: 'blur' },
          {
            pattern: /^1[3-9][0-9]{9}$/,
            message: '手机号格式不对',
            trigger: 'change'
          }
        ],
        loginname: [{ required: true, message: '请输入账号名称', trigger: 'blur' }],
        passwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },

          {
            pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/,
            message: '请输入8-12位数字和字母组合',
            trigger: 'change'
          }
        ],
        repasswd: [{ required: true, validator: repasswd, trigger: 'blur' }],
        roleIds: [{ required: true, message: '请选择所属角色', trigger: 'change' }]
      }, // 表单校验
      nameType: '详情',
      deptIds: [],
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        multiple: true,
        checkStrictly: true,
        emitPath: false
      },
      passwordType: 'password',
      loading: false,
      selectRole: true,
      personType: 1
    };
  },

  mounted() {
    // console.log(this.$route.query);
    this.detail = new Detail(); // 分页
    this.getOptions();
    this.nameType = this.$route.query.nameType;
  },
  methods: {
    async getOptions() {
      try {
        const dept = await getDeptTree({
          withOutAutoCreate: false,
          filterOtherDept: 0
        });
        this.options.dept = dept ? this.getTreeData(dept.data) : {};
      } catch (e) {
        this.options.dept = [];
      }
      if (this.nameType != '新增') {
        this.getDetail();
      }
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          data[i].children = undefined;
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 切换密码显示隐藏
    showPwd(type) {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
    },
    async getDetail() {
      const { data } = await ueserDetail({ id: this.$route.query.id });
      this.detail = {
        name: data.name,
        deptIds: data.deptIds,
        loginname: data.loginname,
        personId: data.personId,
        roleIds: data.roleList.map((i) => {
          return i.id;
        }),
        state: data.state,
        tel: data.tel,
        isCheckUnknownDevice: data.isCheckUnknownDevice,
        id: data.id,
        isDrugLogin: data.isDrugLogin
      };

      // this.detail = data;
      // this.detail.roleIds = data.roleList.map((i) => {
      //   return i.id;
      // });
      this.deptIds = data.deptList.map((i) => {
        return i.id;
      });
      this.detail.deptName = data.deptList.map((i) => {
        return i.name;
      });
      this.detail.deptIds = this.deptIds;
      this.remoteMethod(data.name, data.personId, 'detail');
      console.log(this.detail);
    },
    // 搜索人员列表
    async remoteMethod(query, personId, type) {
      if (query !== '') {
        this.loading = true;
        console.log('ccccccc', query);
        const { data } = await personList({ name: query });
        this.loading = false;
        this.options.personnel = data.list;
        if (type == 'detail') {
          data.list.forEach(ele => {
            if (ele.id == personId) {
              this.personType = ele.personType;
            }
          });
          this.detail.personId = personId;
          this.changeDeptIds();
        }
      } else {
        this.options.personnel = [];
      }
    },
    // 搜索去空格
    trimLR(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    // 改变姓名
    async changeName(e) {
      this.detail.tel = '';
      this.detail.deptIds = [];
      this.detail.roleIds = [];
      // this.detail.yardId = '';
      // console.log(e);
      this.options.personnel.forEach((item, index) => {
        if (e == item.id) {
          // console.log(item);
          this.detail.name = item.name;
          this.detail.tel = item.phone;
          this.personType = item.personType;
          if (item.personType == 2) {
            this.detail.deptIds = item.deptId ? [item.deptId] : [item.yardId];
            this.detail.deptName = item.deptId ? item.deptName : item.yardName;
            // console.log(this.detail.deptIds);
          } else {
            this.detail.deptIds = item.orgIds;
          }
          // this.detail.deptIds = item.orgIds;
          // this.detail.yardId = item.yardId;
        }
      });
      // if (this.detail.deptIds.length == 0) {
      //   const deptIds = await yardDetail({ id: this.detail.yardId });
      //   this.detail.deptIds = [deptIds.data.orgId];
      // }
      this.changeDeptIds();
      // console.log(this.detail.personId);
    },
    // 选择组织
    async changeDeptIds() {
      // console.log('获取角色信息', this.detail.deptIds, this.personType);
      const res = await roleListForYard({ personType: this.personType, personId: this.detail.personId, deptids: this.detail.deptIds });
      console.log(res);
      this.options.role = res.data;
      this.selectRole = false;
    },
    // 提交接口
    async submitBrand() {
      const res = this.nameType == '新增' ? await userAdd({
        ...this.detail
      }) : await userUpdate({
        ...this.detail
      });
      this.$notification('操作成功', 'success', res.msg);
      this.returnUpper();
      // console.log(res);
    },
    // 提交
    createDetail(formName) {
      console.log(this.detail);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let hintText = this.nameType == '新增' ? `新增此账号` : `修改此账号`;
          this.hint('create', hintText);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'create':
              this.submitBrand(row);
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 取消按钮
    closeDialog() { },
    // 返回
    returnUpper() {
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.add {
  background: #fff;
  .addOrderPopout {
    height: 80vh;
    // overflow-y: hidden;
  }
  .input {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 16px;
    // width: 30%;
    ::v-deep.el-form-item__label {
      padding-bottom: 0;
      width: 20%;
      text-align: right;
    }
  }
  ::v-deep.el-dialog {
    height: calc(100vh - 80px);
    overflow-y: auto;
  }
  ::v-deep.el-dialog__body {
    padding: 0 20px 100px;
    position: relative;
  }
}

.el-form--label-left {
  // display: flex;
  // flex-wrap: wrap;
}
.el-form-item {
  display: flex;
  margin-right: 30px;
}
.footer {
  position: absolute;
  right: 50px;
  bottom: 80px;
}
::v-deep.el-form-item--mini .el-form-item__content,
::v-deep.el-form-item--mini .el-form-item__label {
  margin-left: 0 !important;
}
.show-pwd {
  position: absolute;
  right: 15px;
  top: 52%;
  transform: translateY(-52%);
  font-size: 18px;
  color: #ccc;
  cursor: pointer;
  user-select: none;
  display: flex;
}
.svg-icon {
  margin: 2px 0 0 0px;
  font-size: 14px;
}
</style>
